--
-- Author: shunguo.chen
-- Date: 2019-07-23 16:13:16
--
-- PvpEliteController pvp精英赛
--

local EliteMatchSeekView = import("..views.eliteMatch.EliteMatchSeekView")
local EliteMatchBookView = import("..views.eliteMatch.EliteMatchBookView")
local PvpWinView = require("app.pvp.views.PvpWinView")
local BattleFailedView = require("app.system.battlefailed.BattleFailedView")
local PvpDuelTeamView = require("app.pvp.views.PvpDuelTeamView")
local EliteMatchSeasonAwardView = import("..views.eliteMatch.EliteMatchSeasonAwardView")
local PvpLevelView = require("app.pvp.views.PvpLevelView")
local EliteMatchTipsView = import("..views.eliteMatch.EliteMatchTipsView")
local TeamRecruitInfoVo = require("app.team.models.TeamRecruitInfoVo")

local fileName = string.getModeName(...)
local ClassRef = class(fileName, app.mvc.ControllerBase)

function ClassRef:ctor(data)
    self.super.ctor(self, data)
end

function ClassRef:init()
    self._teamModel = app:getInst("TeamModel")


end

function ClassRef:removeListeners()
    self.super.removeListeners(self)

end

function ClassRef:listEvent()
    return {
        "onTeamUpdate",
        "onTeamMemberUpdate",
        "onTeamLeaderChanged",
        "onTeamSettingUpdate",
        "onTeamNewApplyer",
        "onDailyUpdate",
    }
end

function ClassRef:onEvent(eventName, data)
    if eventName == "onTeamUpdate" then -- 队伍更新
        self:_refreshTeamMemberList()
    elseif eventName == "onTeamMemberUpdate" or eventName == "onTeamLeaderChanged" then
        self:_refreshTeamMemberList()
    elseif eventName == "onTeamSettingUpdate" then
        -- 队伍设置更新
        self:updateAutoRecruit()
    elseif eventName == "onTeamNewApplyer" then -- 来新申请人
        if self._teamModel:isMyTeam() then
            self._teamModel:reqGetApplicationList()
        end
        self:refreshNewApplyerFlag()
    elseif eventName == "onDailyUpdate" then
        if UIHandler:isFunctionOpen(Constant.FUNC_TYPE_CS_ELITEMATCH) then
            UD.csEliteMatch:C2S_GetCrossCombatInfo()
            UD.csEliteMatch:clearHistoryChampion()
        end
    end
end

-- 打开精英赛匹配界面
function ClassRef:openView(data)
    -- 跨服副本中，不能进入精英赛
    if DungeonManager:isCrossDungeon() then
        display.pushToast(L("CrossServerTips26"))
        return
    end

    if nil == self._view then
        self._view = EliteMatchSeekView.new(app.mvc.VIEWTYPE_BLUR, data)
        self._view:onCloseView(handler(self, self.closeView))
        self._view:onClearView(handler(self, self.clearView))
        self._view:onOperate(handler(self, self.onOperate))
    end
    self:addChild(self._view, data)

    UD.csEliteMatch:C2S_GetHistoryChampion(data) -- 打开界面先拉取上赛季冠军数据
    self._view:updateSeekView()
    self._view:show()
end
function ClassRef:clearView()
    if self._view then
        self._view = nil
    end
end

--==================================================
        --精英赛
--==================================================

-- 打开精英赛详情界面
function ClassRef:openEliteMatchBookView(data)
    local view = EliteMatchBookView.new(app.mvc.VIEWTYPE_BLUR)
    view:onCloseView(function()
        UIHandler:removeSystemUiByKey(view:getViewName())
    end)
    view:onOperate(handler(self, self.onOperate))
    UIHandler:addSystemUi(view, view:getViewName())
    if data then
        local info = UD.csEliteMatch:getPlayInfoById(data)
        local lv = info.lv
        view:updateBookView(info)
        view:show()
    end
end

-- 打开精英赛排行奖励界面
function ClassRef:openEliteMatchSeasonAwardView(playId)
    local view = EliteMatchSeasonAwardView.new()
    view:onCloseView(function()
        UIHandler:removePopupUiByKey(view:getViewName())
    end)
    view:onOperate(handler(self, self.onOperate))
    UIHandler:addPopupUi(view, view:getViewName())
    view:updateViewByPlayId(playId)
    view:show()
end

-- 打开精英赛决斗场上阵随从界面
function ClassRef:openEliteMatchDuelTeamView()
    local data = {}
    data.myInfo = UD.csEliteMatch:getEliteMatchDuelInfo()
    data.type = "eliteMatch"
    local view = PvpDuelTeamView.new(app.mvc.VIEWTYPE_BLUR, data)
    view:onCloseView(function()
        UIHandler:removeSystemUiByKey(view:getViewName())
    end)
    view:onOperate(handler(self, self.onOperate))
    UIHandler:addSystemUi(view, view:getViewName())
    view:show()

    UD:saveGeneric("eliteMatchChangePartner",true)
end

-- 弹出精英赛胜利界面
function ClassRef:openEliteMatchWinView(data)
    local view
    if data.win then
        view = PvpWinView.new()
        view:refresh(data.rewards, nil, data.type)
    else
        view = BattleFailedView.new()
    end

    view:onCloseView(function()
        UIHandler:removePopupUiByKey(view:getViewName())
        MapManager:setNextChangeMapIgnoreAni(true)
        app.session:request("pb_map.C2S_BackToLastMap",{})

        MapManager:setChangeMapOverCB(function()
            app:sendMsg("PvpController", "openView")
        end)
    end)
    view:onOperate(handler(self, self.onOperate))
    UIHandler:addPopupUi(view, view:getViewName())
    view:show()
end

-- 弹出精英赛赛季等级变化界面
-- type = 1(升级) 3(新赛季)
function ClassRef:openEliteMatchLevelView(data, type)
    local view = PvpLevelView.new()
    view:onCloseView(function(sender)
        if type == 3 then
            if data.lastParticipated then -- 上赛季参与了才显示奖励弹窗
                self:openEliteMatchRewardView(data)
            end
        end
        UIHandler:removePopupUiByKey(sender:getViewName())
    end)
    view:refreshEliteMatch(data, type)
    UIHandler:addPopupUi(view, view:getViewName())
    view:show()
end

-- 弹出上赛季奖励说明弹窗
function ClassRef:openEliteMatchRewardView(data)
    local view = EliteMatchTipsView.new(app.mvc.VIEWTYPE_BLUR, data)
    view:onCloseView(function()
        UIHandler:removePopupUiByKey(view:getViewName())
    end)
    view:onOperate(handler(self, self.onOperate))
    UIHandler:addPopupUi(view, view:getViewName())
    view:refresh()
    view:show()
end

function ClassRef:_refreshTeamMemberList()
    if cc.isDead(self._view) then return end
    self._view:refreshTeamMemberList(self._teamModel:getTeam(), self._teamModel:isNewApplyerFlag())
end

function ClassRef:isEliteMatchSeekShow()
    if not cc.isDead(self._view) then return true end
    return false
end

-- 更新自动申请
function ClassRef:updateAutoApply(teamTarget)
    if cc.isDead(self._view) then return end
    
    self._view:updateAutoApplyStatus(teamTarget)
end

-- 更新自动招募
function ClassRef:updateAutoRecruit(teamTarget)
    if cc.isDead(self._view) then return end
    
    self._view:updateAutoRecruitStatus(teamTarget)
end

-- 刷新推荐队伍里面的申请状态
function ClassRef:refreshTeamListApply(team)
    if cc.isDead(self._view) then return end

    self._view:refreshTeamListApply(team)
end

function ClassRef:refreshNewApplyerFlag()
    if cc.isDead(self._view) then return end

    self._view:refreshNewApplyerFlag( self._teamModel:isNewApplyerFlag() )
end

function ClassRef:onEliteMatchInfoUpdate()
    if cc.isDead(self._view) then return end

    -- 检查赛季等级是否发生变化(跨天后活动玩法会变)
    local info = UD.csEliteMatch:getPlayInfoById(UD.csEliteMatch:getOpenPlayId())
    if self._oldPlayId and self._oldSeasonLv and self._oldPlayId == info.playId and self._oldSeasonLv > info.lv then
        self:openEliteMatchLevelView(info, 1)
    end
    self._oldPlayId = info.playId
    self._oldSeasonLv = info.lv

    -- 检查是否是新赛季(当天开启哪个玩法就检查哪个玩法)
    local lastShowEliteTime = UD:getValueFromGenericByKey("lastShowEliteTime"..info.playId)
    local startTime = info.startTime 
    if not lastShowEliteTime then
        UD:saveGeneric("lastShowEliteTime"..info.playId, startTime)
    elseif tonumber(lastShowEliteTime) < startTime then
        self:openEliteMatchLevelView(info, 3)
        UD:saveGeneric("lastShowEliteTime"..info.playId, startTime)
    end 
end
-------------------------------------------------------
function ClassRef:onOperate(op, ...)
    -- print("ClassRef:onOperate op = " .. op)
    local data = ...
    if op == "refreshTeamList" then -- 拉取组队列表信息       
        local teamTarget = self._teamModel:getTeamTargetById(data)
        if teamTarget and not cc.isDead(self._view) then
            self._view:refreshTeamTarget(teamTarget)
        end
        self._teamModel:C2S_GetTeamList(data, true)
    elseif op == "refreshList" then
        -- 刷新推荐队伍列表 TeamTargetVo
        local teamTarget = data
        self._teamModel:C2S_GetTeamList(teamTarget.id, true)
    elseif op == "refreshEliteMatchMemberList" then --刷新组队信息
        self:_refreshTeamMemberList()
    elseif op == "CombatCross_createTeam" then -- 创建队伍
        local isAutoRecruit = not data:isSingle()
        local recruitInfo = TeamRecruitInfoVo:getCreateRecruitInfo(data.id, isAutoRecruit)
        self._teamModel:reqCreateTeam(recruitInfo)
    elseif op == "reqCombatCrossTeamMatch" then -- 组队匹配
        -- 首先检查队员是否满足匹配条件
        if UD.csEliteMatch:isOpen() then
            UD.csEliteMatch:C2S_CombatCrossCheckMatchCondition(function()
                self:showTeamReady()
            end)
        else
            display.pushToast(L("ErrEventNotStart"))
        end
    elseif op == "CombatCross_cancelMatch" then -- 取消匹配
        self:cancelEliteMatch()
    elseif op == "EliteMatch_showApplyList" then -- 展开申请列表 
        if self._teamModel:isMyTeam() then
            app:sendMsg("NewTeamApplyController", "openView", { 2 } ) -- 弹出标签2-申请标签
        else
            display.pushToast( L("champion_notice1") )
        end
    elseif op == "EliteMatch_quitTeam" then -- 退出队伍
        self._teamModel:reqQuitTeam()
    elseif op == "EliteMatch_TeamSettingUI" then -- 设置UI
        app:sendMsg("NewTeamSettingController", "openView")
    elseif op == "MemberInfoPanel_openInvitePanel" then -- 弹出邀请panel
        app:sendMsg("NewTeamApplyController", "openView", { 1 } ) -- 弹出标签1-邀请标签
    elseif op == "EliteMatch_search" then -- 打开详情界面
        self:openEliteMatchBookView(data)
    elseif op == "changeDuelPartnerStatus" then
        --改变随从的上阵状态
        UD.csEliteMatch:C2S_OnBattlePartnerChange(data.partnerId, data.isOnBattle)
    elseif op == "MemberInfoPanel_partnerOp" then -- 操作随从
        local pos, partnerId = ...
        UIHandler:showHeadMenu( { type=Enums.MenuType.eliteDuel, pos=pos, partnerId=partnerId } )
    elseif op == "QueryNowTeamInfo" then
        UD.csEliteMatch:C2S_QueryNowTeamInfo() -- 如果是精英决斗赛要先请求上阵随从
    elseif op == "autoApply" then
        -- 自动申请 TeamTargetVo isAuto
        local targetId, auto = ...
        local teamTarget = self._teamModel:getTeamTargetById(targetId)
        if teamTarget then
            self._teamModel:C2S_PlayerAutoJoin(teamTarget, auto)
        end
    elseif op == "autoRecruit" then
        -- 自动招募 TeamTargetVo isAuto
        local targetId, auto = ...
        local teamTarget = self._teamModel:getTeamTargetById(targetId)
        if teamTarget then
            self:changeAutoRecruit(teamTarget, auto)
        end
    elseif op == "joinTeam" then
        -- 加入队伍 TeamVo
        local team = ...
        local leaderUid = team:getLeaderUid()
        local targetId = team:getTeamTargetId()
        self._teamModel:reqApplyJoinTeam(leaderUid, targetId, team)
    elseif op == "openOtherSet" then
        -- 打开其他队伍的设置 TeamVo
        local team = ...
        local targetId = team:getTeamTargetId()
        local params = {idx=2, targetId=targetId, team=team}
        app:sendMsg("NewTeamReadyAndSettingController", "openView", params)
    end
end

-- 取消匹配
function ClassRef:cancelEliteMatch()
    if not self._teamModel:isInTeam() or self._teamModel:isMyTeam() then
        UD.csEliteMatch:C2S_CombatCrossCancel()
    else
        local dlg = display.newConfirmDialog( L("CrossServerTips4"),
            function() -- 确定
                self._teamModel:reqQuitTeam()
            end)
        UIHandler:addPopDialog( dlg )
    end
end

function ClassRef:changeAutoRecruit(teamTarget, isAuto)
    if self._teamModel:isInCrossMatch() then
        display.pushToast(L("CrossServerTips24"))
        self:updateAutoRecruit(teamTarget)
        return
    end

    local recruitInfo = self._teamModel:getTeamSettingClone()
    if isAuto then
        local preTargetId = recruitInfo.targetID
        local curTargetId = teamTarget.id
        if preTargetId ~= curTargetId and preTargetId > 0 then
            local msg = string.format(L("lua_code_text_178"), teamTarget:getFullName())
            local dialog = display.newConfirmDialog(msg, 
                function()
                    local preTeamTarget = self._teamModel:getTeamTargetById(preTargetId)
                    if preTeamTarget then
                        preTeamTarget:setAutoRecruit(false)
                    end

                    recruitInfo.targetID = curTargetId
                    recruitInfo.autoRecruit = true
                    self._teamModel:C2S_UpdateRecruitInfo(recruitInfo)
                end,
                function()
                    -- 取消的话，刷新自动招募按钮状态
                    self:updateAutoRecruit(teamTarget)
                end)
            UIHandler:addPopDialog( dialog )
        else
            recruitInfo.targetID = curTargetId
            recruitInfo.autoRecruit = true
            self._teamModel:C2S_UpdateRecruitInfo( recruitInfo )
        end
    else
        recruitInfo.autoRecruit = false
        recruitInfo.targetID = 0
        teamTarget:setAutoRecruit(false)
        self._teamModel:C2S_UpdateRecruitInfo( recruitInfo ) -- 关闭“自动招募”
    end
end

-- 展示战备UI
function ClassRef:showTeamReady()
    local params = {
        idx = 1,
        targetId = Enums.TeamTarget.eliteMatchArena,
        isMatch = true
    }
    app:sendMsg("NewTeamReadyAndSettingController", "openView", params)
end

return ClassRef
